package com.local.web.controller;


import com.local.common.constants.BusinessException;
import com.local.common.constants.ExceptionCodeEnum;
import com.local.common.util.ResultUtil;
import com.local.goods.pojo.Goods;
import com.local.goods.pojo.GoodsESRequestParam;
import com.local.web.service.GoodsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.Map;
import java.util.Objects;

@Controller
@RequestMapping("/goods")
public class GoodsController {

    @Autowired
    private GoodsService goodsService;

    @GetMapping("/{id}")
    public String getById(@PathVariable("id") Integer goodsId, HttpServletRequest request) {
        if (Objects.isNull(goodsId) || goodsId <= 0) {
            throw new BusinessException(
                    ExceptionCodeEnum.PARAM_EXCEPTION.getCode(),
                    ExceptionCodeEnum.PARAM_EXCEPTION.getMessage()
            );
        }

        Goods goods = goodsService.getById(goodsId);

        //商品不存在
        if (Objects.isNull(goods)) {
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_NOT_EXIST.getCode(),
                    ExceptionCodeEnum.GOODS_NOT_EXIST.getMessage()
            );
        }
        //商品已下架
        if (goods.getGoodsSellStatus() == 1) {
            throw new BusinessException(
                    ExceptionCodeEnum.GOODS_PUT_DOWN.getCode(),
                    ExceptionCodeEnum.GOODS_PUT_DOWN.getMessage()
            );
        }

        request.setAttribute("goodsDetail", goods);

        return "mall/goods-detail";
    }


    /**
     * 搜索页面，使用es搜索功能
     * @param keywords
     * @return
     */
    @GetMapping("/search/{keywords}")
    public String search(@PathVariable("keywords") String keywords, HttpServletRequest request) {
        request.setAttribute("keywords", keywords);
        return "mall/goods-search";
    }



    @PostMapping("/searchResult")
    @ResponseBody
    public ResultUtil searchResult(@RequestBody GoodsESRequestParam param) {
        ResultUtil goodsResult = goodsService.search(param);
        return goodsResult;
    }


    /**
     * 搜索的自动补齐，即搜索建议
     * @param param
     * @return
     */
    @PostMapping("/searchSuggestion")
    @ResponseBody
    public ResultUtil<List<String>> searchSuggestion(@RequestBody Map<String, String> param) {
        String keywords = param.get("keywords");
        ResultUtil<List<String>> listResult = goodsService.searchSuggestion(keywords);
        return listResult;
    }
}
